package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.IRoleService;
import com.yt.sys.models.bo.RoleBO;
import com.yt.sys.models.dto.RoleDTO;
import com.yt.sys.models.bo.RoleSaveBO;

import java.util.List;

/**
 * 角色信息控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:47:37
 */

@RestController
@RequestMapping("/api/role")
@Slf4j
@Api(value = "RoleApiController",tags = "角色信息Api接口")
public class RoleApiController {

    @DubboReference
    private IRoleService roleService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<RoleDTO> get(@RequestParam("id") Long id){
        if(id == null){
            Result<RoleDTO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100002.getCode());
            result.setMsg(CodeEnum.FAIL_100002.getMsg());
            return result;
        }

        RoleDTO dto = roleService.selectById(id);
        
        Result<RoleDTO> result = new Result<>();
        result.setData(dto);
        return result;
    }

    @ApiOperation(value = "角色信息列表",notes = "角色信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<RoleDTO>> queryPageList(RoleBO bo){
        Wrapper<RoleDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<RoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = roleService.selectPage(page, wrapper);

        Result<Page<RoleDTO>> result = new Result<>();
        result.setData(page);
        return result;
    }
    
    @ApiOperation(value = "获取所有角色信息", notes = "获取所有角色信息")
    @PostMapping("/listAll")
    public Result<List<RoleDTO>> listAll() {
        List<RoleDTO> roleList = roleService.selectList(null);
        
        Result<List<RoleDTO>> result = new Result<>();
        result.setData(roleList);
        return result;
    }
    
    @ApiOperation(value = "新增角色", notes = "新增角色")
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody RoleSaveBO saveBO) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (saveBO == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空");
                return result;
            }
            
            // 执行新增操作
            boolean operationResult = roleService.add(saveBO);
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("新增角色成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("新增角色失败");
            }
            return result;
        } catch (Exception e) {
            log.error("新增角色异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("新增角色异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "修改角色", notes = "修改角色")
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody RoleSaveBO saveBO) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (saveBO == null || saveBO.getId() == null || saveBO.getId().trim().isEmpty()) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空，角色ID不能为空");
                return result;
            }
            
            // 先查询角色是否存在
            Long roleId;
            try {
                roleId = Long.valueOf(saveBO.getId());
            } catch (NumberFormatException e) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("角色ID格式不正确");
                return result;
            }
            
            RoleDTO existingRole = roleService.selectById(roleId);
            if (existingRole == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("角色不存在");
                return result;
            }
            
            // 将RoleSaveBO转换为RoleDTO
            RoleDTO roleDTO = new RoleDTO();
            roleDTO.setId(roleId);
            roleDTO.setRoleName(saveBO.getRoleName());
            roleDTO.setRoleDes(saveBO.getRoleDes());
            roleDTO.setStatus(saveBO.getStatus());
            
            // 执行更新操作
            boolean operationResult = roleService.updateById(roleDTO);
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("修改角色成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("修改角色失败");
            }
            return result;
        } catch (Exception e) {
            log.error("修改角色异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("修改角色异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "删除角色", notes = "删除角色")
    @PostMapping("/delete")
    @ApiImplicitParam(name = "id", value = "角色ID", required = true, paramType = "query", dataType = "Long")
    public Result<Boolean> delete(@RequestParam("id") Long id) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (id == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空，角色ID不能为空");
                return result;
            }
            
            // 先查询角色是否存在
            RoleDTO existingRole = roleService.selectById(id);
            if (existingRole == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("角色不存在");
                return result;
            }
            
            // 执行删除操作
            boolean operationResult = roleService.deleteById(id);
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("删除角色成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("删除角色失败");
            }
            return result;
        } catch (Exception e) {
            log.error("删除角色异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("删除角色异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "根据角色ID或名称查询角色", notes = "根据角色ID或名称查询角色，支持模糊查询")
    @PostMapping("/search")
    public Result<List<RoleDTO>> search(@RequestParam(value = "keyword", required = true) String keyword) {
        try {
            Result<List<RoleDTO>> result = new Result<>();
            // 参数校验
            if (keyword == null || keyword.trim().isEmpty()) {
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg(CodeEnum.FAIL_100002.getMsg());
                return result;
            }
            
            // 构造查询条件
            Wrapper<RoleDTO> wrapper = new EntityWrapper<>();
            wrapper.like("id", keyword).or().like("role_name", keyword);
            
            // 执行查询
            List<RoleDTO> roleList = roleService.selectList(wrapper);
            
            result.setData(roleList);
            return result;
        } catch (Exception e) {
            log.error("根据角色ID或名称查询角色异常", e);
            Result<List<RoleDTO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("查询异常：" + e.getMessage());
            return result;
        }
    }
}